package vendor_account

import (
	"bytes"
	"math/rand"
	"micro-oauth/utils"
	"text/template"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

const pwdInitTemplate = `
你好：<br>
	你的BOH账户<b>{{.account}}</b>的初始密码为<b>{{.pwd}}</b>
	<br><br>若你没有过相关操作，请忽略此邮件。（该邮件为自动发送，请勿回复)
	<br><br>
	合阔智云(Hex Cloud)
`

const pwdResetTemplate = `
你好：<br><br>
	你的BOH账户<b>{{.account}}</b>的密码已经重置为<b>{{.pwd}}</b>
	<br><br>若你没有过相关操作，请忽略此邮件。（该邮件为自动发送，请勿回复)
	<br><br>
	合阔智云(Hex Cloud)
`

func SendPwdInitEmail(mailAddr string, account string, pwd string) error {
	data := map[string]string{
		"account": account,
		"pwd":     pwd,
	}
	temp, err := template.New("initPwd").Parse(pwdInitTemplate)
	if err != nil {
		return err
	}
	var doc bytes.Buffer
	err = temp.Execute(&doc, data)
	if err != nil {
		return err
	}
	emailContent := doc.String()
	err = utils.SendEmail(mailAddr, emailContent, "密码初始化")
	if err != nil {
		return err
	}
	return nil
}

func SendPwdResetEmail(mailAddr string, account string, pwd string) error {
	data := map[string]string{
		"account": account,
		"pwd":     pwd,
	}
	temp, err := template.New("resetPwd").Parse(pwdResetTemplate)
	if err != nil {
		return err
	}
	var doc bytes.Buffer
	err = temp.Execute(&doc, data)
	if err != nil {
		return err
	}
	emailContent := doc.String()
	err = utils.SendEmail(mailAddr, emailContent, "密码重置")
	if err != nil {
		return err
	}
	return nil
}

const validatePwdChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

func RandomPwd() string {
	var pwd = ""
	randLen := rand.Intn(10) + 6
	for i := 0; i < randLen; i++ {
		randInt := rand.Intn(len(validatePwdChars))
		pwd += validatePwdChars[randInt : randInt+1]
	}
	return pwd
}

func RandomCode() string {
	return utils.GenUniqueToken(RandomPwd())
}
